#include "tcpserver.h"
#include <QDebug>

TcpServer::TcpServer(QObject *parent) :
    QObject(parent)
{
    connect(&server, SIGNAL(newConnection()),
        this, SLOT(acceptConnection()));

      server.listen(QHostAddress::Any, 8888);
      //client = NULL;
}

TcpServer::~TcpServer()
{
  server.close();
}

void TcpServer::acceptConnection()
{
    qDebug()<<"TcpServer::acceptConnection()";

    QTcpSocket* client = server.nextPendingConnection();
    TcpClientManager *clientManager = new TcpClientManager;
    clientManager->setTcpClient(client);
    _clients.append(clientManager);
    emit acceptedConnection();

    connect(clientManager, SIGNAL(receivedMessage(QByteArray)),
        this, SLOT(receiveMessage(QByteArray))
    );
}

void TcpServer::receiveMessage(QByteArray message)
{
    emit receivedMessage(message);
}

void TcpServer::sendData(QByteArray data)
{
    qDebug()<<"TcpServer::sendData(QByteArray data)";
    TcpClientManagersIterator_ptr it = _clients;
    int index = 0;
    while(it.hasNext())
    {
        qDebug()<<"client: "<<index;
        TcpClientManager *item = it.next();
        if(item->getTcpClient()!=NULL)
        {
            qDebug()<<"sending data";
            item->sendData(data);
            index++;
        }
        else
        {
            qDebug()<<"The client number "<<index<<"is no longer valid, it will be removed and deleted";
            _clients.removeAt(index);
            delete item;
        }
    }
}

